// KrautWiimote.cpp : Defines the entry point for the console application.
//

#include "WiiYourself/wiimote.h"
#include "KrautMobil.h"
#include "error.h"
#include <time.h>
#include <cstdlib> 

// ------------------------------------------------------------------------------------
//  state-change callback example (we use polling for everything else):
// ------------------------------------------------------------------------------------
void on_state_change(wiimote &remote, state_change_flags changed,
      const wiimote_state &new_state) {
   // ----------------------------------------------------------------------------------------------------------
   // At this point, "remote" still contains the old state. We can compare new_state to the state of "remote"
   // Make sure to use new_state below in order to check if buttons have been pressed etc.

   if ( (changed & BUTTONS_CHANGED) == BUTTONS_CHANGED )
   {
      if ( new_state.Button.Two() && ! remote.Button.Two() ) {
         std::cout << "2" << std::endl;
      }
   }


   // ----------------------------------------------------------------------------------------------------------
   // Calling RefreshState will copy the new state to the wiimote object so that new_state == state of wiimote.
   remote.RefreshState();
}

int main(int argc, char* argv[]) {


   while (42) {
      wiimote wii;
      wii.CallbackTriggerFlags = (state_change_flags) (CONNECTED
            | ORIENTATION_CHANGED | ACCEL_CHANGED | BUTTONS_CHANGED
            | CONNECTION_LOST);
      wii.ChangedCallback = on_state_change;
      try {
         if (!wii.Connect()) {
            std::cerr << "Connection to wiimote failed" << std::endl;
         }
      } catch (exception e) {
         if (!wii.IsConnected()) {
            std::cerr << "Connection to wiimote failed: " << e.what()
                  << std::endl;
            continue;
         }
      }
      if (!wii.IsConnected()) {
         Sleep(500);
         continue;
      }

      std::cout << "Wiimote connected" << std::endl;

      while (wii.IsConnected()) {
         Sleep(200);
      }
      std::cout << "Wiimote connection lost" << std::endl;
   }

   return 0;
}

